package com.chenxin.wms.process.outbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chenxin.common.annotation.WmsLogs;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.enums.WmsBusinessStatus;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.ObDetailEntity;
import com.chenxin.wms.domain.ObMasterEntity;
import com.chenxin.wms.mapper.ObDetailMapper;
import com.chenxin.wms.mapper.ObMasterMapper;
import com.chenxin.wms.process.outbound.IProcStockPrepareByDetail;
import com.chenxin.wms.process.outbound.IProcStockPrepareByMaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProcStockPrepareByMaster implements IProcStockPrepareByMaster {
    @Autowired
    private ObMasterMapper obMasterMapper;
    @Autowired
    private ObDetailMapper obDetailMapper;
    @Autowired
    private IProcStockPrepareByDetail procStockPrepareByDetail;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @WmsLogs(name = "出库主单自动备货")
    public ProcResult call(Long obMasterId, Long creator) {
        // 根据主单ID获取相关明细进行备货处理
        if (StringUtils.isNull(obMasterId)) {
            return ProcResult.error("pre_master_err001", "主单ID不能为空");
        }
        // 通过ID获取主单信息
        ObMasterEntity obMasterInfo = obMasterMapper.selectById(obMasterId);
        if (obMasterInfo == null) {
            return ProcResult.error("pre_master_err002", "主单ID【" + obMasterId + "】不存在");
        }
        // 根据单据状态判断是否需要继续备货
        int obMasterStatus = obMasterInfo.getObMasterStatus();
        if (obMasterStatus > 1) {
            return ProcResult.error("pre_master_err003", "主单状态【" + obMasterStatus + "】不允许继续备货");
        }
        // 获取备货明细列表（只匹配尚未备货完成的单据）
        QueryWrapper<ObDetailEntity> detailByIdQW = new QueryWrapper<>();
        detailByIdQW.lambda().eq(ObDetailEntity::getObMasterId, obMasterId)
                .le(ObDetailEntity::getObDetailStatus, WmsBusinessStatus.OB_DETAIL_PREPARED.getCode());
        List<ObDetailEntity> details = obDetailMapper.selectList(detailByIdQW);
        // 判断是否仍有需要备货的明细
        if (details == null || details.size() == 0) {
            return ProcResult.error("pre_master_err004","主单【" + obMasterId + "】没有需要备货的明细");
        }
        // 循环处理明细备货
        for (ObDetailEntity detail : details) {
            try {
                ProcResult result = procStockPrepareByDetail.call(detail.getObDetailId(), creator);
                if (!WmsConstants.PROC_SUCCESS.equals(result.getCode())) {
                    throw new WmsException("pre_master_err005", "主单【" + obMasterId + "】备货异常，causeBy:" + result.getMessage());
                }
            } catch (WmsException e) {
                // 处理明细异常，不影响后续明细处理
                throw new WmsException(e.getCode(), e.getMessage());
            }
        }
        // 更新主单相关状态（主单状态与明细最低级别状态保持一致）
        QueryWrapper<ObDetailEntity> minStatusQW = new QueryWrapper<>();
        minStatusQW.lambda().eq(ObDetailEntity::getObMasterId, obMasterId)
                .orderByAsc(ObDetailEntity::getObDetailStatus).last("limit 1");
        ObDetailEntity obDetail = obDetailMapper.selectOne(minStatusQW);

        UpdateWrapper<ObMasterEntity> statusUW = new UpdateWrapper<>();
        statusUW.lambda().eq(ObMasterEntity::getObMasterId, obMasterId)
                .set(ObMasterEntity::getObMasterStatus, obDetail.getObDetailStatus());

        return ProcResult.success("主单【" + obMasterId + "】成功备货");
    }
}
